#!/usr/bin/php -q
<?php 
// vim:set fdm=indent ts=2 ai et sts=2 sw=2 tw=0:
// simple database query class by $Author: anton $ 
// $Date: 2008-02-26T03:31:53.279063Z $
// iread.php
// 資料庫程式 功能定義 $URL
//  Released as a GPL licensed software.

include("inc/config.php");
include("inc/class.db.php");
include("inc/dict.php");
include("inc/xml.php");
include("inc/weather.php");

$UNLiuline              = File2Array("cin/UNLiu.cin");
$Array30line            = File2Array("cin/Array30.cin");
$CangJieline            = File2Array("cin/CangJie.cin");
$ZhuYinline             = File2Array("cin/ZhuYin-Big.cin");

if ($argc>=3) // Commit 成功才輸出
{
  $isadmin   = false;
  $iscommand = false;
  mb_internal_encoding("UTF-8");
  $temp = explode("/",$argv[1]);
  $stripped_from = $temp[0]; unset($temp);
  $from = $argv[1];
  $body = "";
  for ($i=2;$i<$argc;$i++)
    $body .= $argv[$i]." ";
  if (substr($body,strlen($body)-1,1)==" ")
    $body = substr($body,0,strlen($body)-1);
  if (strncmp($from,ADMIN,strlen(ADMIN))==0) $isadmin   = true;
  if (substr($body,0,1)=="#")      $iscommand = true;

  if ($iscommand)
  {
    if (@preg_match("/^#([^\ ]*) (.*)/",$body,$temp))
      $command = $temp[1];
    else
      preg_match("/^#([^\ ]*)/",$body,$temp);
  } else {
    if (@preg_match("/^([^\ ]*) (.*)/",$body,$temp))
      $command = $temp[1];
    else
      preg_match("/^([^\ ]*)/",$body,$temp);
  }
  $command = $temp[1];
  $word    = $temp[2]; 

  $ans = "";
  switch ($command)
  {
    case "do":
    unset($output);
    mesg($from,"您的指令是: '$word'\n");
    if ($isadmin)
    {
      exec($word,$output);
      for($i=0;$i<count($output);$i++)
        $ans.=$output[$i]." <br />\n";
      mesg($from,$ans);
    } else {
      mesg($from,$from."非管理員耶...\n");
    }
    break;

    case "no":
    case "嘸":
    mesg($from,UNLiu($word));
    break;

    case "help":
    case "問":
    mesg($from,COMMON_HELP);
    break;

    case "sysop":
    case "救命":
    case "請問":
    mesg(ADMIN,"$from 留言說:$word");
    break;

    case "weather":
    case "天氣":
    require_once("inc/eac_curl.class.php");
    $ans = GetWeather($word);
    mesg($from,$ans);
    break;

    case "jp":
    $ans = jpdict($word);
    $all = explode("【",$ans);
    for ($i=0;$i<count($all);$i++)
    {
      $ans = "【".$all[$i];
      $msglen = mb_strlen($ans);
      if ($msglen>256)
      {
        while ($msglen>256)
        {
          echo $ans_part."\n";
          $ans_part = mb_substr($ans,0,256);
          mesg($from,$ans_part);
          $ans = mb_substr($ans,(-1)*($msglen-256));
          $msglen = mb_strlen($ans);
        }
          mesg($from,$ans);
      } else {
          mesg($from,$ans);
      }
    }
    unset ($all);
    break;

    case "dict":
    case "字典":
    $ans = dict($word); 
    mesg($from,$ans);
    break;

    case "stock":
    if (strlen($word)>12)  // 暫時的防呆
    {
      mesg($from,"字串過長"); 
      break;
    }
    $db = new DBData();
    include("inc/db_config.php");
    $db->INIT();
    $sql = "SELECT `stockid` FROM `stocklist` WHERE `name` like '%$word%' OR `stockid`='$word';";
    $data = $db->SQL($sql);
    if (count($data)>0)
    {
      for ($i=0;$i<count($data);$i++)
      {
        $ans .= stock($data[$i][stockid]);
        if (!$ans) $ans .= "找不到該股票編號，如確定編號無誤，請通知管理員補上。";
      } 
    } else {
      $ans .= "找不到該股票編號，如確定編號無誤，請通知管理員補上。";
    }
    unset($data);
    mesg($from,$ans);
    $db->END();
    break;

    default:
    // 思考系統
    $db = new DBData();
    include("inc/db_config.php");
    $db->INIT();
    // 先記整句
    $keyword_arr = Array();
    $now = time();
    $sql = "INSERT INTO `sentense` (`id`, `sentense`, `meanings`, `enlarge`, `lessen`, `time`, `prop`) VALUES('', '$body', '', '', '', '$now', 'unknown');";
    $db->SQL($sql);
    // 取得關鍵句
    $sql = "SELECT `phrase` FROM `phrase` WHERE 1 ORDER BY `time` DESC LIMIT 0,100"; // 只記得最近留下來的關鍵字就好
    $data = $db->SQL($sql);
    $num  = count($data);
    if ($num<100)
    { // 關鍵字不夠的話，用(100)常用字處理
      // 抓常用字 TODO
      echo "#關鍵字不足\n";
      if ($num>0) // 0 就什麼也不跑吧...
      for ($i=0;$i<$num;$i++)
        array_push($keyword_arr, $data[$i][phrase]);
    } else {
      for ($i=0;$i<100;$i++)
        array_push($keyword_arr,$data[$i][phrase]);
    }
    // 追加 mb 的切割單字
    $mb_num = mb_strlen($body);
    for ($i=0;$i<$mb_num;$i++)
    {
      $word1 = mb_substr($body,$i,1);
      array_push($keyword_arr,$word1);
    }
    unset($word1);

    // 留下關鍵字
    for ($i=1;$i<count($keyword_arr);$i++) // 1 是 null
    {
      $keyword_length = mb_strlen($keyword_arr[$i]);
      for ($x=0;$x<mb_strlen($body);$x++)
      {
        // 塞 keyowrd 
        if (mb_substr($body,$x,$keyword_length)==$keyword_arr[$i])
        {
          if (mb_substr($body,$x-1,1))
          {
            WordUpdate($keyword_arr[$i],mb_substr($body,$x-1,1));
            $sql = "INSERT INTO `phrase` (`id`, `phrase`, `meanings`, `relative`, `time`) VALUES('', '".$keyword_arr[$i]."', '".md5($keyword_arr[$i])."', '".$keyword_arr[$i-1]."', '$now')";
          } else if (mb_substr($body,$x+1,1))
          {
            WordUpdate($keyword_arr[$i],mb_substr($body,$x+1,1));
            $sql = "INSERT INTO `phrase` (`id`, `phrase`, `meanings`, `relative`, `time`) VALUES('', '".$keyword_arr[$i]."', '".md5($keyword_arr[$i])."', '".$keyword_arr[$i+1]."', '$now')";
          } else
          {
            WordUpdate($keyword_arr[$i],null);
            $sql = "INSERT INTO `phrase` (`id`, `phrase`, `meanings`, `time`) VALUES('', '".$keyword_arr[$i]."', '".md5($keyword_arr[$i])."', '$now')";
          }
          $db->SQL($sql);
        }
      }
    }
    // 留下暫存
    $sql = "INSERT INTO `tempinput` (`id`, `input`, `enlarge`, `lessen`, `keyword`, `whosaid`, `time`) VALUES('', '$body', '', '', '$body', '$stripped_from', '$now');";
    $db->SQL($sql);

    $db->END();
    break;
  } // end of switch
} else {
  echo "argc <3";
}

function mesg($to,$mesg)
{
  $mesg = strip_tags($mesg);
  $mesg = str_replace("\n\n\n","\n",$mesg);
  $mesg = str_replace("'","`",$mesg);
  echo $mesg;
}
function File2Array($filename)
{
  if (filesize($filename)>0)
  {
    $fs=fopen($filename,"r");
    $content=fread($fs,filesize($filename));
    fclose($fs);
    $arr = explode("\n",$content);
    unset($content);
  } else {
    $fs=fopen($filename,"w");
    fclose($fs);
    $arr = array();
  }

  for ($i=0;$i<count($arr);$i++)
    if ($arr[$i]=="") array_splice($arr,$i,1);
  return $arr;
}
function WordUpdate($word,$relative)
{
  global $db;
  $now = time();
  $sql = "SELECT `id`,`freq` FROM `word` WHERE `word`='$word' AND `relative`='$relative' LIMIT 0,1";
  $data = $db->SQL($sql);
  if ($data==null) 
  {
    if ($relative!=null)
      $sql = "INSERT INTO `word` (`word`, `relative`, `prop`, `time`, `freq`) VALUES ('$word', '$relative', 'u', '$now', '0')";
    else
      $sql = "INSERT INTO `word` (`word`, `relative`, `prop`, `time`, `freq`) VALUES ('$word', '', 'u', '$now', '0')";
    $db->SQL($sql);
  } else {
    $sql = "UPDATE `word` SET `freq`=(`freq`+1) WHERE `id`='".$data[0][id]."' ";
    $db->SQL($sql);
  }
}
?>
